import json
from django_redis import get_redis_connection

from carts import constants
from carts import meiduo_json
from goods.models import SKU
from meiduo_mall.utils.response_code import RETCODE
from django import http
from django.shortcuts import render
from django.views import View


class CartsView(View):
    def get(self, request):
        # 购物车商品展示
        # 处理
        user = request.user
        if user.is_authenticated:
            redis_conn = get_redis_connection('carts')
            cart_redis_dicts = redis_conn.hgetall('carts%d' % user.id)
            selecteds = redis_conn.smembers('selected%d' % user.id)
            cart_dict = {}
            for sku_id, count in cart_redis_dicts.items():
                cart_dict[int(sku_id)] = {
                    'count': int(count),
                    'selected': sku_id in selecteds
                }

        else:
            cart_str = request.COOKIES.get('cart')
            if not cart_str == None:
                cart_dict = meiduo_json.loads(cart_str)
            else:
                return render(request, 'cart.html')
        # 去数据库中查询需要的数据
        skus = SKU.objects.filter(pk__in=cart_dict.keys())
        sku_list = []
        for sku in skus:
            # print(cart_dict, cart_dict[sku.id].get('count',1))
            sku_list.append({
                'id': sku.id,
                'name': sku.name,
                'price': str(sku.price),
                'default_image_url': sku.default_image.url,
                'count': cart_dict[sku.id]['count'],
                'selected': str(cart_dict[sku.id]['selected'])
            })
        context = {
            'cart_skus': sku_list
        }
        # 响应
        return render(request, 'cart.html', context)

    def post(self, request):
        # 添加购物车
        param_dict = json.loads(request.body.decode())
        sku_id = param_dict.get('sku_id')
        count = param_dict.get('count')
        selected = param_dict.get('selected', True)
        # 验证
        if not all([sku_id, count]):
            return http.JsonResponse({'code': RETCODE.PARAMERR, 'errmsg': '参数不全'})
        try:
            SKU.objects.get(pk=sku_id, is_launched=True)

        except:
            return http.JsonResponse({'code': RETCODE.PARAMERR, 'errmsg': '库存商品编号无效'})
        try:
            count = int(count)
        except:
            return http.JsonResponse({'code': RETCODE.PARAMERR, 'errmsg': '数量错误'})
        if count < 1:
            return http.JsonResponse({'code': RETCODE.PARAMERR, 'errmsg': '数量必须大于１'})
        # if selected
        response = http.JsonResponse({'code': RETCODE.OK, 'errmsg': 'ok'})
        user = request.user
        if user.is_authenticated:
            redis_conn = get_redis_connection('carts')
            redis_pl = redis_conn.pipeline()
            # 添加ｈａｓｈ用户ｉｄ　商品　数量
            key = 'carts%d' % user.id
            redis_pl.hset(key, sku_id, count)
            # 添加ｓｅｔ用户ｉｄ，商品,添加默认选中
            redis_pl.sadd('selected%d' % user.id, sku_id)
            redis_pl.execute()

        else:
            cart_str = request.COOKIES.get('cart')
            if not cart_str == None:
                # 读取并添加到ｃｏｏｋｉｅ
                cart_dict = meiduo_json.loads(cart_str)
                cart_dict[sku_id] = {
                    'count': count,
                    'selected': selected
                }
                json_cart_dict = meiduo_json.dumps(cart_dict)
                response.set_cookie('cart', json_cart_dict, max_age=constants.CART_EXPIRES)
            else:
                # 添加

                cart_dict = {}
                cart_dict[sku_id] = {
                    'count': count,
                    'selected': selected
                }
                json_cart_dict = meiduo_json.dumps(cart_dict)
                response.set_cookie('cart', json_cart_dict, max_age=constants.CART_EXPIRES)

        return response

    def put(self, request):
        # 修改
        param_dict = json.loads(request.body.decode())
        sku_id = param_dict.get('sku_id')
        count = param_dict.get('count')
        selected = param_dict.get('selected', True)
        # 验证
        if not all([sku_id, count]):
            return http.JsonResponse({'code': RETCODE.PARAMERR, 'errmsg': '参数不全'})
        try:
            sku = SKU.objects.get(pk=sku_id, is_launched=True)
        except:
            return http.JsonResponse({'code': RETCODE.PARAMERR, 'errmsg': '库存商品编号无效'})
        try:
            count = int(count)
        except:
            return http.JsonResponse({'code': RETCODE.PARAMERR, 'errmsg': '数量错误'})
        if count < 1:
            return http.JsonResponse({'code': RETCODE.PARAMERR, 'errmsg': '数量必须大于１'})
            # if selected
        if not isinstance(selected, bool):
            return http.JsonResponse({'code': RETCODE.PARAMERR, 'errmsg': '选中状态有误'})
        user = request.user
        response = http.JsonResponse({
            'code': RETCODE.OK,
            'errmsg': 'ok',
            'cart_sku': {
                'id': sku_id,
                'count': count,
                'selected': str(selected),
                'name': sku.name,
                'price': str(sku.price),
                'default_image_url': sku.default_image.url,
            }
        })

        if user.is_authenticated:
            # 修改ｈａｓｈ用户ｉｄ　商品　数量
            # 　修改ｓｅｔ用户ｉｄ，商品,添加默认选中
            redis_conn = get_redis_connection('carts')
            redis_pl = redis_conn.pipeline()
            redis_pl.hset('carts%d' % user.id, sku_id, count)
            if selected:
                redis_pl.sadd('selected%d' % user.id, sku_id)
            else:
                redis_pl.srem('selected%d' % user.id, sku_id)
            redis_pl.execute()


        else:

            cart_str = request.COOKIES.get('cart')
            # 读取并添加到ｃｏｏｋｉｅ
            if not cart_str == None:
                cart_sku = meiduo_json.loads(cart_str)
                cart_sku[sku_id] = {
                    'id': sku_id,
                    'count': count,
                    'selected': str(selected),
                    'name': sku.name,
                    'price': str(sku.price),
                    'default_image_url': sku.default_image.url,
                }
            else:
                cart_sku = {}

            json_cart_dict = meiduo_json.dumps(cart_sku)
            response.set_cookie('cart', json_cart_dict, max_age=constants.CART_EXPIRES)

        return response

    def delete(self, request):
        sku_id = json.loads(request.body.decode()).get('sku_id')
        if not all([sku_id]):
            return http.JsonResponse({'code': RETCODE.PARAMERR, 'errmsg': '参数不全'})
        try:
            sku = SKU.objects.get(pk=sku_id, is_launched=True)
        except:
            return http.JsonResponse({'code': RETCODE.PARAMERR, 'errmsg': '库存商品编号无效'})
        user = request.user
        response = http.JsonResponse({'code': RETCODE.OK, 'errmsg': 'ok'})
        if user.is_authenticated:
            # 修改ｈａｓｈ用户ｉｄ　商品　数量
            # 　修改ｓｅｔ用户ｉｄ，商品,添加默认选中
            redis_conn = get_redis_connection('carts')
            redis_pl = redis_conn.pipeline()
            redis_pl.hdel('carts%d' % user.id, sku_id)
            redis_pl.srem('selected%d' % user.id, sku_id)
            redis_pl.execute()

        else:
            cart_str = request.COOKIES.get('cart')
            if not cart_str == None:
                # 读取并添加到ｃｏｏｋｉｅ
                cart_dict = meiduo_json.loads(cart_str)
                if sku_id in cart_dict:
                    del cart_dict[sku_id]
            else:
                cart_dict = {}
            json_cart_dict = meiduo_json.dumps(cart_dict)
            response.set_cookie('cart', json_cart_dict, max_age=constants.CART_EXPIRES)

        return response
        # 删除ｈａｓｈ用户ｉｄ　商品　数量
        # 删除ｓｅｔ用户ｉｄ，商品,添加默认选中


class CartsSelectionView(View):
    def put(self, request):
        # 接受
        selected = json.loads(request.body.decode()).get('selected')
        # 验证
        if not isinstance(selected, bool):
            return http.JsonResponse({'code': RETCODE.PARAMERR, 'errmsg': '选中状态有误'})
        # 处理
        user = request.user
        response = http.JsonResponse({'code': RETCODE.OK, 'errmsg': 'ok'})
        if user.is_authenticated:
            redis_conn = get_redis_connection('carts')
            if selected:
                sku_ids = redis_conn.hkeys('carts%d' % user.id)
                redis_conn.sadd('selected%d' % user.id, *sku_ids)
            else:
                sku_ids = redis_conn.hkeys('carts%d' % user.id)
                redis_conn.srem('selected%d' % user.id, *sku_ids)
        else:
            # 获取ｃｏｏｋｉｅ解码为字典
            cart_str =request.COOKIES.get('cart')
            if cart_str == None:
                cart_str = {}
            else:
                cart_dict = meiduo_json.loads(cart_str)
                for sku_id in cart_dict:
                    cart_dict[sku_id]['selected'] = selected

            json_cart_dict = meiduo_json.dumps(cart_dict)
            response.set_cookie('cart', json_cart_dict, max_age=constants.CART_EXPIRES)
        # 响应
        return response

class CartsSimpleView(View):
    def get(self, request):
        # id 购物车SKU编号
        # name 购物车SKU名称
        # count 购物车SKU数量
        # default_image_url 购物车SKU图片
        user = request.user
        cart_skus = []
        if user.is_authenticated:
            # 通过user.id 获取所有的sku_id及sku_id包含的数量

            redis_conn = get_redis_connection('carts')
            user_dicts = redis_conn.hgetall('carts%d'% user.id)
            for sku_id, sku_count in user_dicts.items():
                sku = SKU.objects.get(pk=int(sku_id))  # skus不会
                count = int(sku_count)
                cart_skus.append({
                    'id': int(sku_id),
                    'name': sku.name,
                    'count': count,
                    'default_image_url': sku.default_image.url
                })

        else:
            '''cart_dict[sku_id] = {
                    'count': count,
                    'selected': selected
                }'''
            mjson_cart_dict = request.COOKIES.get('cart')
            if not mjson_cart_dict:
                pass
            else:
                cart_dict = meiduo_json.loads(mjson_cart_dict)
                for sku_id, sku_dict in cart_dict.items():
                    sku = SKU.objects.get(pk=int(sku_id))
                    cart_skus.append({
                        'id': sku_id,
                        'name': sku.name,
                        'count': sku_dict.get('count'),
                        'default_image_url': sku.default_image.url
                    })
        return http.JsonResponse({'code': RETCODE.OK, 'errmsg': 'ok', 'cart_skus': cart_skus})

# Create your views here.
